<template>
	<view class="register">
		<u-navbar back-text="用户注册" :background="{
				background: 'transparent'
			}"></u-navbar>
		<view class="formbox">
			<u-form :model="form" label-position="top" ref="uForm">
				<u-form-item label="邀请人" v-if="invInfo.img !== ''">
					<view class="topcenter u-flex u-row-center u-col-center u-flex-wrap" style="width: 200rpx;margin: 0 auto 40rpx auto;">
						<u-avatar :src="invInfo.img" mode="circle" :size="200" style="margin-bottom: 16rpx;"></u-avatar>
						<view class="">{{ invInfo.user }}</view>
					</view>
					<u-line color="#BBBBBB"></u-line>
				</u-form-item>
				<u-form-item label="邀请码" prop="code">
					<u-input v-model="form.code" placeholder="请输入6位邀请码" />
				</u-form-item>
				<u-form-item label="手机号" prop="phone">
					<u-input v-model="form.phone" placeholder="请输入手机号" />
				</u-form-item>
				<u-form-item label="验证码" prop="phone_code">
					<u-input v-model="form.phone_code" placeholder="请输入验证码" />
					<text slot="right" @click="getCode" style="color: #F2682C;font-size: 28rpx;">{{ codeTips }}</text>
				</u-form-item>
			</u-form>
			<view class="radiobox u-flex u-row-left u-col-center">
				<u-checkbox-group>
					<u-checkbox v-model="isagree" shape="circle" :size="24"><text style="font-size: 24rpx;">我已阅读并同意</text></u-checkbox>
				</u-checkbox-group>
				<text style="color: #F2682C;" @click="gouseragree">《京推优选用户协议》</text>
			</view>
			<view class="" style="margin-top: 82rpx;">
				<u-button shape="circle" :ripple="true" :hair-line="false" ripple-bg-color="rgba(255,255,255,0.3)" :custom-style="{
						backgroundColor: '#F2682C',
						color: '#FFFFFF',
						fontWeight: 600
					}"
				 @click="doRegister">
					<text class="bold" style="font-size: 36rpx;">提 交</text>
				</u-button>
			</view>
		</view>
		<u-toast ref="uToast"></u-toast>
		<u-verification-code seconds="60" ref="uCode" @change="codeChange"></u-verification-code>
	</view>
</template>

<script>
	export default {
		name: 'register',
		data() {
			return {
				isagree: false,
				codeTips: '',
				// refCode: null,
				seconds: 60,
				form: {
					code: '',
					phone: '',
					phone_code: '',
					user: '',
					openId: '',
					img: '',
					applets_id: ''
				},
				invInfo: {
					user: '',
					img: ''
				},
				rules: {
					code: [{
							required: true,
							message: '请输入邀请码',
							// 可以单个或者同时写两个触发验证方式
							trigger: ['blur', 'change']
						},
						{
							len: 6,
							message: '邀请码为6位',
							trigger: 'change'
						}
					],
					phone: [{
							required: true,
							message: '请输入手机号',
							trigger: ['change', 'blur']
						},
						{
							validator: (rule, value, callback) => {
								// 上面有说，返回true表示校验通过，返回false表示不通过
								// this.$u.test.mobile()就是返回true或者false的
								return this.$u.test.mobile(value);
							},
							message: '手机号码不正确',
							// 触发器可以同时用blur和change
							trigger: ['change', 'blur']
						}
					],
					phone_code: [{
							required: true,
							message: '请输入手机验证码',
							// 可以单个或者同时写两个触发验证方式
							trigger: ['blur', 'change']
						},
						{
							len: 6,
							message: '验证码为6位',
							trigger: 'change'
						}
					]
				}
			};
		},
		watch: {
			'form.code': function(val) {
				if (val.length === 6) {
					this.getInvitationCode();
				}
			}
		},
		//实例创建完成后被立即调用
		created() {},
		onLoad(option) {},
		//挂载开始之前被调用
		beforeMount() {},
		onPullDownRefresh() {
			//监听下拉刷新动作的执行方法，每次手动下拉刷新都会执行一次
			// console.log('refresh');
			// setTimeout(function() {
			// 	uni.stopPullDownRefresh(); //停止下拉刷新动画
			// }, 1000);
		},
		//初次渲染完成
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		//全局只触发一次
		onLaunch() {},
		//从后台进入前台
		onShow() {
			if (uni.getStorageSync('invitecode')) {
				this.form.code = uni.getStorageSync('invitecode');
				this.getInvitationCode();
			}
		},
		//前台进入后台
		onHide() {},
		methods: {
			getInvitationCode(num) {
				this.$u.api
					.getInvitationCode({
						code: this.form.code
					})
					.then(res => {
						if (res.code == 200) {
							this.invInfo.user = res.data.user;
							this.invInfo.img = res.data.img;
							if (num === 2) {
								this.$u.api
									.doRegister(this.form)
									.then(res => {
										console.log(res);
										this.$refs.uToast.show({
											title: '注册成功!',
											type: 'success'
										});
										uni.setStorageSync('isloginout', true);
										uni.setStorageSync('isregister', true);
										setTimeout(() => {
											uni.navigateBack({
												delta: 1
											});
										}, 1000);
									})
									.catch(err => {
										this.$refs.uToast.show({
											title: err.msg,
											type: 'error'
										});
									});
							}
						} else {
							this.invInfo.user = '';
							this.invInfo.img = '';
							this.$refs.uToast.show({
								title: res.msg,
								type: 'error'
							});
						}
					})
					.catch(err => {
						this.invInfo.user = '';
						this.invInfo.img = '';
						this.$refs.uToast.show({
							title: err.msg,
							type: 'error'
						});
					});
			},
			gouseragree() {
				uni.navigateTo({
					url: '/pages/center/register/userAgreement'
				});
			},
			doRegister() {
				if (!this.isagree) {
					this.$refs.uToast.show({
						title: '请同意《京推优选用户协议》!',
						type: 'warning'
					});
					return;
				}
				// console.log('userInfo', uni.getStorageSync('userInfo'));
				this.form.user = uni.getStorageSync('userInfo').nickName;
				this.form.openId = uni.getStorageSync('openid');
				this.form.img = uni.getStorageSync('userInfo').avatarUrl;
				this.form.applets_id = uni.getAccountInfoSync().miniProgram.appId;

				this.$refs.uForm.validate(valid => {
					if (valid) {
						console.log('验证通过', this.form);
						if (this.form.user === '' || this.form.user === null || this.form.user === undefined) {
							this.$refs.uToast.show({
								title: '授权信息获取失败',
								type: 'error'
							});
						} else {
							this.$u.api
								.doRegister(this.form)
								.then(res => {
									console.log(res);
									this.$refs.uToast.show({
										title: '注册成功!',
										type: 'success'
									});
									uni.setStorageSync('isloginout', true);
									uni.setStorageSync('isregister', true);
									setTimeout(() => {
										uni.navigateBack({
											delta: 1
										});
									}, 1000);
								})
								.catch(err => {
									console.log(err);
									this.$refs.uToast.show({
										title: err.msg,
										type: 'error'
									});
								});
						}
					} else {
						this.$refs.uToast.show({
							title: '请检查表单填写!',
							type: 'error'
						});
					}
				});
			},
			codeChange(text) {
				this.codeTips = text;
			},
			getCode() {
				if (this.$u.test.mobile(this.form.phone)) {
					if (this.$refs.uCode.canGetCode) {
						// 模拟向后端请求验证码
						uni.showLoading({
							title: '正在获取验证码'
						});
						this.$u.api
							.getPhoneCode({
								phone: this.form.phone
							})
							.then(res => {
								// console.log(res);
								uni.hideLoading();
								// 这里此提示会被this.start()方法中的提示覆盖
								this.$u.toast('验证码已发送');
								// 通知验证码组件内部开始倒计时
								this.$refs.uCode.start();
							})
							.catch(err => {
								console.log(err);
								this.$refs.uToast.show({
									title: err.msg,
									type: 'error'
								});
							});
					} else {
						this.$u.toast('倒计时结束后再发送');
					}
				} else {
					this.$u.toast('请检查手机号填写是否正确!');
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.register {
		background-color: #f7f7f8;
		min-height: 100vh;

		.formbox {
			padding: 0 66rpx;
		}
	}
</style>
